
import os
import subprocess
import json
import getpass


def qad_client_script_hfldvl(program_name, in_path, trace_id):
    data = {

    }
    os.environ['DLC'] = r'/apps/oe117/dlc'

    p = subprocess.Popen(["stty", "intr", "^c"])
    p.wait()
    p = subprocess.Popen(". %s; echo LD_LIBRARY_PATH=$LD_LIBRARY_PATH; "
                         "echo SHLIB_PATH=$SHLIB_PATH; echo LIBPATH=$LIBPATH; "
                         "echo PROLIBPATH=$PROLIBPATH" % os.path.join(r'/apps/oe117/dlc', 'bin', 'slib_env'),
                         stdout=subprocess.PIPE, shell=True, universal_newlines=True)
    output = p.communicate()[0]
    environ = dict(line.split("=", 1) for line in output.splitlines())
    os.environ.update(environ)

    os.environ['PATH'] = os.path.join(r'/apps/oe117/dlc', 'bin') + ':' + os.environ['PATH']

    os.environ[r'AVMMEMORY2'] = r'1'

    if 'PROMSGS' not in os.environ:
        os.environ['PROMSGS'] = os.path.join(r"/apps/oe117/dlc", "promsgs")

    if 'PROTERMCAP' not in os.environ:
        os.environ['PROTERMCAP'] = os.path.join(r"/apps/oe117/dlc", "protermcap")
    os.environ['PS1'] = str(os.getpid())
    os.environ['PROPATH'] = r'/apps/ee2022/dvl/config,' \
                            r'/apps/ee2022/dvl/build/catalog/packages/qracore/3/23/2/0/qad.qra.core/bin/qracore.pl,' \
                            r'/apps/ee2022/dvl/dist/mfg-customizations,' \
                            r'/apps/ee2022/dvl/dist/mfg,' \
                            r'/apps/ee2022/dvl/dist/mfg/us/xx,' \
                            r'/apps/ee2022/dvl/dist/fin/proxypatch,' \
                            r'/apps/ee2022/dvl/dist/pro/com/mfgpro,' \
                            r'/apps/ee2022/dvl/build/catalog/packages/fin-bin64-proxy/2022/1/6/1/proxy.pl,' \
                            r'/apps/ee2022/dvl/dist/pro,.,' \
                            r'/apps/ee2022/dvl/build/catalog/packages/service-interface-foundation/1/1/220/0/lib/qra.pl,' \
                            r'/apps/ee2022/dvl/dist/mfg,/apps/ee2022/dvl/dist/mfg/us,' \
                            r'/apps/ee2022/dvl/dist/mfg/us/bbi'
    os.environ['APPDIR'] = r'/apps/ee2022/dvl'

    # if len(sys.argv) > 1:
    #     codepage = sys.argv[1]
    # else:
    codepage = 'cp936'
    startup_params = ''

    if codepage == 'utf-8':
        startup_params = '-ucc -utf8intatchar ' + startup_params

    if 'TERM' not in os.environ:
        os.environ['TERM'] = input("Please enter your terminal type: ")

    if 'USER' not in os.environ:
        os.environ['USER'] = getpass.getuser()

    program = os.path.expandvars(r'com/qad/qra/core/ClientBootstrap.p -param startup='
                                 + program_name +
                                 r',logfile=/apps/ee2022/dvl/build/logs/client/session-chui-${USER}.log')

    params = [os.path.join(r"/apps/oe117/dlc", "bin", "_progres"), "-pf",
              r'/apps/ee2022/dvl/config/bootstrap.pf'] \
             + startup_params.split() + \
             ["-cpinternal", codepage, "-cpstream", codepage, "-p"] + program.split()
    pcwd = os.path.abspath(os.path.expandvars(os.path.expanduser(r'/home/mfg')))
    p = subprocess.Popen(params, cwd=pcwd)

    run_status = p.wait()

    in_path = in_path.replace('cim/', 'out/')
    with open(in_path + trace_id + '.run.log', 'r', encoding='cp936') as runlog:
        for line in runlog:
            # print(line)
            if line.find("**") >= 0 or line.find("error") >= 0:
                data['error_msg'] = line
                data['status'] = 'Failed'
                return data, False

    try:
        with open(in_path + trace_id + '.run.out.json', 'r', encoding='utf-8') as runlog1:
            data = json.load(runlog1)
        return data, True
    except FileNotFoundError:
        return data, False
